<?php


namespace Appstore\Controller;

use Appstore\Model;
use Think\Controller;
use Vendor\requester;

class AdminController extends BaseController
{
    public function _initialize()
    {
        if (!is_login()) {
            $this->error('请登陆后再发布。将跳转到登陆页面。', U('Ucenter/member/login'));
        }
        $this->getPercent();
        parent::_initialize();
    }

    public function index()
    {

        $this->display();
    }

    public function myGoods()
    {
        $aPayed = I('get.payed', 1, 'intval');

        $map['pay_ok'] = $aPayed;
        $map['uid'] = get_uid();
        $map['status'] = 1;
        $order_list = D('AppstoreOrder')->order('pay_time desc')->where($map)->select();
        $goods_list = $already = array();
        $versionModel = D('AppstoreVersion');
        $goodsModel = D('AppstoreGoods');
        foreach ($order_list as &$val) {
            if (!in_array($val['version_id'], $already)) {
                $already[] = $val['version_id'];
                $goods = $goodsModel->find($val['goods_id']);
                $goods['version'] = $versionModel->find($val['version_id']);
                $val['goods'] = $goods;
            }
        }
        $this->assign('order_list', $order_list);
        $this->assign('payed', $aPayed);
        //dump($goods_list);exit;
        $this->display();
    }


    public function order()
    {

        $aId = I('post.keywords', 0);
        $aId && $map['id'] = array('like', '%' . $aId . '%');
        $map['uid'] = get_uid();
        $order_list = D('AppstoreOrder')->order('pay_time desc')->where($map)->select();
        $versionModel = D('AppstoreVersion');
        $goodsModel = D('AppstoreGoods');
        foreach ($order_list as &$v) {
            $goods = $goodsModel->getById($v['goods_id']);
            $v['goods'] = '[' . $v['goods_id'] . ']' . $goods['title'];
            $version = $versionModel->getVersion($v['version_id']);
            $v['version'] = '[' . $v['version_id'] . '] V' . $version['title'];
            $v['status'] = $v['status'] ? '<span style="color: green">正常</span>' : '<span style="color: red">已取消</span>';
            $v['pay_ok'] = $v['pay_ok'] ? '<span style="color: green">已支付</span>' : '<span style="color: red">未支付</span>';
            $score = D('Ucenter/Score')->getType(array('id' => $v['score']));
            $v['score'] = '[' . $v['score'] . ']' . $score['title'];
            $v['payment_price'] = $v['payment_price'] . $score['unit'];
        }
        $this->assign('order_list', $order_list);
        $this->display();
    }

    /**
     * 云码兑换
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function incode()
    {
        $this->checkActionLimit('appstore_incode', 'Appstore', null, get_uid());
        $aCode = I('post.code', '', 'text');
        $map['code'] = $aCode;
        $map['status'] = 1;
        $codeModel = D('Appstore/AppstoreCode');
        $code = $codeModel->getCode($map);
        if (!$code) {
            $this->error('该云码不存在或已禁用，请输入正确云码！');
        }
        $codeModel->setStatus($map, 2); //设置云码已使用

        //设置云码使用信息表start
        $data['code_id'] = $code['id'];
        $data['create_time'] = time();
        $data['uid'] = get_uid();
        D('Appstore/AppstoreCodeUse')->add($data);
        //设置云码使用信息表end

        //创建订单
        D('Appstore/AppstoreOrder')->createOrderList(array('status' => 1), explode(',', $code['version_ids']));
        action_log('appstore_incode', 'Appstore', null, get_uid());
        $this->success('兑换成功！', U('Appstore/Admin/myGoods'));
    }

    public function bind()
    {
        $websiteModel = D('AppstoreWebsite');
        /*if ($websiteModel->isBinded(get_uid())) {
            $this->error('您已经绑定过。请不要重复绑定。');
        }*/

        if (IS_POST) {
            $aIsChecked = I('post.is_checked', 0, 'intval');
            if (!$aIsChecked) {
                $this->error('请先验证域名');
            }

            $isBinded = $websiteModel->isBinded(get_uid());
            if ($isBinded) {
                $this->error('您已经绑定过域名，无法再次绑定。');
            }

            $aDomain = I('post.domain', '', 'text');
            $aTitle = I('post.title', '', 'text');
            $aMaster = I('post.master', '', 'text');
            if ($aDomain === '') {
                $this->error('请填写域名。');
            }

            if ($websiteModel->checkWebsiteIsExist($aDomain)) {
                $this->error('该域名已经被其他用户绑定，无法再次绑定。');
            }

            $return = $this->visitUrl($aDomain);
            if ($return[0] != 200) {
                $this->error('网址验证失败');
            }


            if ($aTitle === '') {
                $this->error('请填写标题。');
            }
            if ($aMaster === '') {
                $this->error('请填写网站持有人。');
            }

            $has = $websiteModel->where(array('domain' => $aDomain))->count();
            if ($has) {
                $this->error('域名已经被其他用户绑定。请更换域名。');
            }
            $website['uid'] = is_login();
            $website['create_time'] = time();
            $website['status'] = 1;
            $website['domain'] = $aDomain;
            $website['title'] = $aTitle;
            $website['master'] = $aMaster;
            $rs = $websiteModel->add($website);
            if ($rs === false) {
                $this->error('数据库写入失败。');
            } else {
                $this->success('网站绑定成功。', $_SERVER['HTTP_REFERER']);
            }
        } else {
            $website = $websiteModel->where(array('uid' => get_uid()))->find();
            $this->assign('website', $website);
            $this->display();
        }
    }

    public function  addversion($id = 0)
    {
        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {

            $aId = I('post.goods_id', 0, 'intval');
            if (empty($_POST)) {
                $this->error('您所上传的文件过大。');
            }
            if (!$form->validate()) {
                $this->error('验证不通过。');
            };
            $id = intval(I('get.id'));
            $goods = D('AppstoreGoods')->find($id);
            if ($goods['uid'] != is_login() && !is_administrator()) {
                $this->error('404');
            }

            $aNeedbuy = I('post.need_buy', '0', 'intval');

            $version['title'] = op_t(I('post.title'));
            $version['create_time'] = time();
            $version['log'] = op_t(I('post.log'));
            $version['status'] = 1;
            $version['update_time'] = time();
            $version['need_buy'] = $aNeedbuy;
            $version['goods_id'] = $id;
            $version['pack'] = intval(I('post.pack'));

            $result = D('AppstoreVersion')->add($version);


            if ($aNeedbuy) {
                $version['id'] = $result;
                $this->addPrice($version);
                D('AppstoreGoods')->where(array('id' => $aId))->setField('need_buy', 1);
            }


            D('AppstoreGoods')->where(array('id' => $aId))->setField('update_time', time());
            D('AppstoreResource')->where(array('id' => $aId))->setField('latest_version', $version['title']);
            if ($result) {
                $type = array(1 => 'plugin', 2 => 'module', 3 => 'theme', 4 => 'service');
                //todo 推送更新消息
                $watched = D('AppstoreWatch')->getWatched($id);
                D('Common/Message')->sendMessage(getSubByKey($watched, 'uid'), '订阅的商品版本更新推送', "商品《{$goods['title']}》发布了最新版【{$version['title']}】，赶紧去看看吧！", 'Appstore/Index/' . $type[$goods['entity']] . 'detail', array('id' => $id), get_uid(), 2);
                $this->success('添加成功。', U('index/' . $type[$goods['entity']] . 'detail', array('id' => $id)));
            } else {
                $this->error('添加失败。');
            }
        } else {
            $id = intval($id);
            if ($id == 0) {
                $this->error('404');
            }
            //检查所有者
            $goods = D('AppstoreGoods')->find($id);
            if ($goods['uid'] != is_login()) {
                $this->error('404');
            }
            if ($goods['entity'] == 1) {
                $this->assign('entity', '插件');
            }
            /*构建表单*/
            /*名称 title 字段*/
            $form->add('label', 'label_goodstitle', 'goodstitle', '当前更新的商品', null);
            $obj = $form->add('text', 'goodstitle', $goods['title'], array('readonly' => 'readonly'));
            $obj->set_rule(array(
                'readonly' => 1,
            ));
            // 默认显示上一个版本的价格方案
            $last_version = D('AppstoreVersion')->where(array('goods_id' => $id))->order('id desc')->find();
            $form = $this->getMoney($form, $last_version);
            $form->add('label', 'label_title', 'title', '版本号', null);
            $obj = $form->add('text', 'title', '');
            $obj->set_rule(array(
                'required' => array('error', '版本号必须填写。'),
                'length' => array(2, 20, 'error', '长度必须在2-20个字之间。')
            ));
            $form->add('note', 'note_title', 'title', '版本号，必须为 1.0.0 格式，否则无法自动升级！详细说明<a target="_blank" href="http://blog.csdn.net/ccj2020/article/details/7833035">linux版本号命名法</a>', array('style' => 'width:400px'));
            /*日志 log 字段*/
            $form->add('label', 'label_log', 'log', '更新日志');
            $obj = $form->add('textarea', 'log', '', array('autocomplete' => 'off', 'style' => 'width:500px'));
            $obj->set_rule(array(
                'required' => array('error', '必须填写更新日志，否则小伙伴搞不清楚的哟。'),
                'length' => array(0, 5000, 'error', '不得超过500个字', true)
            ));
            $form->add('note', 'note_log', 'log', '必填，填写更新日志，例如修复了什么？增加了什么？', array('style' => 'width:400px'));
            /*日志 log 字段*/
            $form->add('hidden', 'goods_id', $goods['id']);
            /*图标cover 字段*/
            $form->add('label', 'label_cover', 'pack', '文件');
            $obj = $form->add('wuploader', 'pack');
            // set rules
            $obj->set_rule(array(
                'image' => array('error', '图标必须为 jpg, png or gif !'),
                'filesize' => array(1024000, 'error', '图标不能超过 10MB!'),
                'filetype' => array('zip', 'error', '文件类型不允许')
            ));
            $form->add('note', 'note_pack', 'pack', '只允许zip格式，否则无法解压。不能超过10MB，超过请上传至第三方网盘。');
            $form->clientside_validation(
                array(
                    'close_tips' => false, //  don't show a "close" button on tips with error messages
                    'on_ready' => false, //  no function to be executed when the form is ready
                    'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                    'scroll_to_error' => true, //  don't scroll the browser window to the error message
                    'tips_position' => 'right', //  position tips with error messages to the right of the controls
                    'validate_on_the_fly' => true, //  don't validate controls on the fly
                    'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
                )
            );
            // 提交按钮
            $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));
            /*渲染*/
            $form = $form->render('*horizontal', true);
            $this->assign('form', $form);
            $this->assign('data', $goods);
            $this->display();
        }
    }
    public function  addsolution($id = 0)
    {
        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {

            $aId = I('post.goods_id', 0, 'intval');
            if (empty($_POST)) {
                $this->error('您所上传的文件过大。');
            }
            if (!$form->validate()) {
                $this->error('验证不通过。');
            };
            $id = intval(I('get.id'));
            $goods = D('AppstoreGoods')->find($id);
            if ($goods['uid'] != is_login() && !is_administrator()) {
                $this->error('404');
            }

            $aNeedbuy = I('post.need_buy', '0', 'intval');

            $version['title'] = op_t(I('post.title'));
            $version['create_time'] = time();
            $version['log'] = op_t(I('post.log'));
            $version['status'] = 1;
            $version['update_time'] = time();
            $version['need_buy'] = $aNeedbuy;
            $version['goods_id'] = $id;
            $version['pack'] = intval(I('post.pack'));

            $result = D('AppstoreVersion')->add($version);


            if ($aNeedbuy) {
                $version['id'] = $result;
                $this->addPrice($version);
                D('AppstoreGoods')->where(array('id' => $aId))->setField('need_buy', 1);
            }


            D('AppstoreGoods')->where(array('id' => $aId))->setField('update_time', time());
            D('AppstoreResource')->where(array('id' => $aId))->setField('latest_version', $version['title']);
            if ($result) {
                $type = array(1 => 'plugin', 2 => 'module', 3 => 'theme', 4 => 'service');
                //todo 推送更新消息
                $watched = D('AppstoreWatch')->getWatched($id);
                D('Common/Message')->sendMessage(getSubByKey($watched, 'uid'), '订阅的商品版本更新推送', "商品《{$goods['title']}》发布了最新版【{$version['title']}】，赶紧去看看吧！", 'Appstore/Index/' . $type[$goods['entity']] . 'detail', array('id' => $id), get_uid(), 2);
                $this->success('添加成功。', U('index/' . $type[$goods['entity']] . 'detail', array('id' => $id)));
            } else {
                $this->error('添加失败。');
            }
        } else {
            $id = intval($id);
            if ($id == 0) {
                $this->error('404');
            }
            //检查所有者
            $goods = D('AppstoreGoods')->find($id);
            if ($goods['uid'] != is_login()) {
                $this->error('404');
            }
            if ($goods['entity'] == 1) {
                $this->assign('entity', '插件');
            }
            /*构建表单*/
            /*名称 title 字段*/
            $form->add('label', 'label_goodstitle', 'goodstitle', '当前更新的商品', null);
            $obj = $form->add('text', 'goodstitle', $goods['title'], array('readonly' => 'readonly'));
            $obj->set_rule(array(
                'readonly' => 1,
            ));
            // 默认显示上一个版本的价格方案
            $last_version = D('AppstoreVersion')->where(array('goods_id' => $id))->order('id desc')->find();
            $form = $this->getMoney($form, $last_version);
            $form->add('label', 'label_title', 'title', '方案名', null);
            $obj = $form->add('text', 'title', '');
            $obj->set_rule(array(
                'required' => array('error', '方案名必须填写。'),
                'length' => array(2, 20, 'error', '长度必须在2-20个字之间。')
            ));

            $obj = $form->add('textarea', 'log', '', array('autocomplete' => 'off', 'style' => 'width:500px'));
            $obj->set_rule(array(
                'length' => array(0, 500, 'error', '不得超过500个字', true)
            ));
            $form->add('note', 'note_log', 'log', '简单说明。', array('style' => 'width:400px'));
            /*日志 log 字段*/
            $form->add('hidden', 'goods_id', $goods['id']);
            /*图标cover 字段*/

            $form->clientside_validation(
                array(
                    'close_tips' => false, //  don't show a "close" button on tips with error messages
                    'on_ready' => false, //  no function to be executed when the form is ready
                    'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                    'scroll_to_error' => true, //  don't scroll the browser window to the error message
                    'tips_position' => 'right', //  position tips with error messages to the right of the controls
                    'validate_on_the_fly' => true, //  don't validate controls on the fly
                    'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
                )
            );
            // 提交按钮
            $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));
            /*渲染*/
            $form = $form->render('*horizontal', true);
            $this->assign('form', $form);
            $this->assign('data', $goods);
            $this->display();
        }
    }
    private function addPrice($version)
    {
        $pid = 0;
        $priceModel = D('AppstorePrice');
        $aPrice = I('post.price');
        if (empty($aPrice['value'][0])) {
            $this->error('请至少添加一个价格方案');
        }
        foreach ($aPrice['is_parent'] as $key => $val) {
            $data['version_id'] = $version['id'];
            $data['goods_id'] = $version['goods_id'];

            if ($val) {
                $data['pid'] = 0;
                $data['key'] = 'score';
                $data['value'] = $aPrice['value'][$key];
                $data['price'] = $aPrice['price'][$key];
                $data['price_type'] = $aPrice['price_type'][$key];
                $pid = $priceModel->add($data);
            } else {
                if ($pid) {
                    $data['pid'] = $pid;
                    $data['key'] = 'role';
                    $data['value'] = $aPrice['value'][$key];
                    $data['price'] = $aPrice['price'][$key];
                    $data['price_type'] = $aPrice['price_type'][$key];
                    $priceModel->add($data);
                }
            }

        }
    }

    public function editVersion()
    {
        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {

            $aNeedbuy = I('post.need_buy', '0', 'intval');

            if (empty($_POST)) {
                $this->error('您所上传的文件过大。');
            }
            if (!$form->validate()) {
                $this->error('验证不通过。');
            };
            $id = I('get.id', 0, 'intval');

            $version = D('AppstoreVersion')->getVersion($id);

            $goods = D('AppstoreGoods')->find($version['goods_id']);


            $this->checkAuth('Appstore/Admin/manage', $goods['uid']);

            $now_time = time();
            $version['title'] = I('post.title', '', 'text');
            $version['log'] = I('post.log', '', 'text');
            $version['status'] = 1;
            $version['update_time'] = $now_time;
            $version['need_buy'] = $aNeedbuy;
            $version['pack'] = I('post.pack', '0', 'intval');


            $priceModel = D('AppstorePrice');
            $priceModel->where(array('version_id' => $version['id']))->delete();
            if ($aNeedbuy) {
                $this->addPrice($version);
                D('AppstoreGoods')->where(array('id' => $version['goods_id']))->setField('need_buy', 1);
            } else {
                D('AppstoreGoods')->where(array('id' => $version['goods_id']))->setField('need_buy', 0);
            }


            $result = D('AppstoreVersion')->save($version);


            D('AppstoreGoods')->where(array('id' => $version['goods_id']))->setField('update_time', time());
            D('AppstoreResource')->where(array('id' => $version['goods_id']))->setField('latest_version', $version['title']);

            if ($result === false) {
                $this->error('修改失败。');
            } else {
                $type = array(1 => 'plugin', 2 => 'module', 3 => 'theme', 4 => 'service');
                $watched = D('AppstoreWatch')->getWatched($version['goods_id']);
                D('Common/Message')->sendMessage(getSubByKey($watched, 'uid'), '订阅的商品版本更新推送', "商品《{$goods['title']}》调整了版本【{$version['title']}】信息，赶紧去看看吧！", 'Appstore/Index/' . $type[$goods['entity']] . 'detail', array('id' => $version['goods_id']), get_uid(), 2);
                $this->success('修改成功。', U('index/' . $type[$goods['entity']] . 'detail', array('id' => $version['goods_id'])));
            }


        } else {

            $aId = I('get.id', 0, 'intval');

            if ($aId == 0) {
                $this->error('404');
            }

            $version = D('AppstoreVersion')->getVersion($aId);
            //检查所有者

            $goods = D('AppstoreGoods')->find($version['goods_id']);

            $this->checkAuth('Appstore/Admin/manage', $goods['uid']);

            if ($goods['entity'] == 1) {
                $this->assign('entity', '插件');
            }
            /*构建表单*/
            /*名称 title 字段*/
            $form->add('label', 'label_goodstitle', 'goodstitle', '当前更新的商品', null);
            $obj = $form->add('text', 'goodstitle', $goods['title'], array('readonly' => 'readonly'));
            $obj->set_rule(array(
                'readonly' => 1,
            ));
            $form = $this->getMoney($form, $version);
            $form->add('label', 'label_title', 'title', '版本号', null);
            $obj = $form->add('text', 'title', $version['title']);
            $obj->set_rule(array(
                'required' => array('error', '版本号必须填写。'),
                'length' => array(2, 20, 'error', '长度必须在2-20个字之间。'),
            ));
            $form->add('note', 'note_title', 'title', '版本号，必须为 1.0.0 格式，否则无法自动升级！详细说明<a target="_blank" href="http://blog.csdn.net/ccj2020/article/details/7833035">linux版本号命名法</a>', array('style' => 'width:400px'));
            /*日志 log 字段*/
            $form->add('label', 'label_log', 'log', '更新日志');
            $obj = $form->add('textarea', 'log', $version['log'], array('autocomplete' => 'off', 'style' => 'width:500px'));
            $obj->set_rule(array(
                'required' => array('error', '必须填写更新日志，否则小伙伴搞不清楚的哟。'),
                'length' => array(0, 5000, 'error', '不得超过500个字', true)
            ));
            $form->add('note', 'note_log', 'log', '必填，填写更新日志，例如修复了什么？增加了什么？', array('style' => 'width:400px'));
            /*日志 log 字段*/
            $form->add('hidden', 'goods_id', $goods['id']);
            /*图标cover 字段*/
            $form->add('label', 'label_cover', 'pack', '文件');
            $obj = $form->add('wuploader', 'pack', $version['pack']);
            // set rules
            $obj->set_rule(array(
                'image' => array('error', '图标必须为 jpg, png or gif !'),
                'filesize' => array(1024000, 'error', '图标不能超过 10MB!'),
                'filetype' => array('zip', 'error', '文件类型不允许')
            ));
            $form->add('note', 'note_pack', 'pack', '只允许zip格式，否则无法解压。不能超过10MB，超过请上传至第三方网盘。');
            $form->clientside_validation(
                array(
                    'close_tips' => false, //  don't show a "close" button on tips with error messages
                    'on_ready' => false, //  no function to be executed when the form is ready
                    'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                    'scroll_to_error' => true, //  don't scroll the browser window to the error message
                    'tips_position' => 'right', //  position tips with error messages to the right of the controls
                    'validate_on_the_fly' => true, //  don't validate controls on the fly
                    'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
                )
            );
            // 提交按钮
            $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));
            /*渲染*/
            $form = $form->render('*horizontal', true);
            $this->assign('form', $form);
            $this->assign('data', $goods);


            $this->display('addversion');

        }

    }


    public function delVersion()
    {
        $aVersionId = I('get.id', 0, 'intval');

        $good = get_goods_by_versionid($aVersionId);
        $this->checkAuth('Appstore/Admin/manage', $good['uid']);
        $res = D('AppstoreVersion')->where(array('id' => $aVersionId))->setField('status', 0);
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**统一转发函数，通过判断对象类别来转发到对应的函数
     * @param int $id
     * @auth 陈一枭
     */
    public function add($id = 0)
    {
        $good = D('AppstoreGoods')->find(intval($id));
        switch ($good['entity']) {
            case 1:
                redirect(U('addplugin?id=' . $good['id']));
                break;
            case 2:
                redirect(U('addmodule?id=' . $good['id']));
        }
    }


    private function iniDev()
    {
        $dev = array('status' => 1, 'uid' => get_uid());
        D('AppstoreDeveloper')->add($dev, null, 1);
    }


    public function  addplugin($id = 0)
    {

        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {
            // 验证表单
            if ($form->validate()) {
                $base = array(); //基本数据
                $resource = array(); //资源数据
                $plugin = array(); //插件数据
                $id = intval($id);
                if ($id != 0) {
                    $base = D('AppstoreGoods')->find($id);
                    $this->checkPermission($base); //检查权限，防止越权修改
                    $base = $this->getBaseData($base);
                    D('AppstoreGoods')->save($base);
                    $resource = $this->getResourceData($base['id'], $resource);
                    D('AppstoreResource')->save($resource);
                    $plugin = $this->getPluginData($base['id'], $plugin);
                    D('AppstorePlugin')->save($plugin);
                    $this->success('插件数据修改成功。', U('index/goodsDetail', array('id' => $id)));
                } else {

                    $base = $this->getBaseData($base);
                    $base['uid'] = get_uid();
                    $base['entity'] = 1;
                    $base['create_time'] = time();
                    $base = $this->getGoodsStatus($base);

                    $goods_id = D('AppstoreGoods')->add($base);
                    if ($goods_id == 0) {
                        $this->error('创建失败。');
                    }
                    $resource = $this->getResourceData($goods_id, $resource);
                    D('AppstoreResource')->add($resource);
                    $plugin = $this->getPluginData($goods_id, $plugin);
                    $result = D('AppstorePlugin')->add($plugin);

                    $this->iniDev();

                    $user = query_user(array('nickname'));
                    $admin_uids = explode(',', C('USER_ADMINISTRATOR'));
                    if ($base['status'] == 2) {
                        foreach ($admin_uids as $admin_uid) {
                            D('Common/Message')->sendMessage($admin_uid, $title = '应用商店插件提交提醒', "{$user['nickname']}提交了新的插件《{$base['title']}》，请到后台审核。", 'admin/appstore/verify', array(), is_login(), 2);
                        }
                        $this->success('插件创建成功。请耐心等待审核，在此期间，您可以上传一个版本，只有审核通过，且有新版本的插件才能够显示在前台。', U('index/pluginDetail', array('id' => $goods_id)));
                    } else {
                        $this->success('插件创建成功。', U('index/pluginDetail', array('id' => $goods_id)));
                    }


                }

            } else {
                $this->error('验证失败');
            }

        } else {


            $id = intval($id);
            $data = null;
            if ($id != 0) {
                $data = D('AppstorePlugin')->getById($id);

            }
            $this->checkCreatePermission($data);
            $obj = $this->buildBaseForm($form, $data, 1);


            /*插件扩展字段*/
            /*名称 title 字段*/
            $form->add('label', 'label_hook', 'hook', '调用到的钩子');
            $obj = $form->add('text', 'hook', $data['hook'], array('autocomplete' => 'off', 'style' => 'width:350px'));
            $obj->set_rule(array(
                'required' => array('error', '请填写调用到的钩子。')
            ));
            $form->add('note', 'note_hook', 'hook', '必填，请填写您的插件所调用到的钩子，多个用空格分隔。', array('style' => 'width:350px'));

            $this->buildEditor($form, $data);

            $form->clientside_validation(
                array(
                    'close_tips' => false, //  don't show a "close" button on tips with error messages
                    'on_ready' => false, //  no function to be executed when the form is ready
                    'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                    'scroll_to_error' => true, //  don't scroll the browser window to the error message
                    'tips_position' => 'right', //  position tips with error messages to the right of the controls
                    'validate_on_the_fly' => true, //  don't validate controls on the fly
                    'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
                )
            );
            // 提交按钮
            $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));

            /*渲染*/
            $form = $form->render('*horizontal', true, array('class' => 'form-horizontal'));
            $this->assign('current', 'plugin');
            $this->assign('data',$data);
            $this->assign('form', $form);
            $this->display();
        }


    }

    public function addtheme($id = 0)
    {
        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {
            // 验证表单
            if ($form->validate()) {
                $base = array(); //基本数据
                $resource = array(); //资源数据
                $theme = array(); //插件数据
                $id = intval($id);
                if ($id != 0) {
                    $base = D('AppstoreGoods')->find($id);
                    $this->checkPermission($base); //检查权限，防止越权修改
                    $base = $this->getBaseData($base);
                    D('AppstoreGoods')->save($base);
                    $resource = $this->getResourceData($base['id'], $resource);
                    D('AppstoreResource')->save($resource);
                    $theme = $this->getThemeData($base['id'], $theme);
                    D('AppstoreTheme')->save($theme);
                    $this->success('商品数据修改成功。', U('index/goodsDetail', array('id' => $id)));
                } else {

                    $base = $this->getBaseData($base);
                    $base['uid'] = get_uid();
                    $base['entity'] = 3;
                    $base['create_time'] = time();
                    $base = $this->getGoodsStatus($base);
                    $goods_id = D('AppstoreGoods')->add($base);
                    if ($goods_id == 0) {
                        $this->error('创建失败。');
                    }
                    $resource = $this->getResourceData($goods_id, $resource);
                    D('AppstoreResource')->add($resource);
                    $theme = $this->getModuleData($goods_id, $theme);
                    $result = D('AppstoreTheme')->add($theme);

                    $this->iniDev();


                    $user = query_user(array('nickname'));
                    $admin_uids = explode(',', C('USER_ADMINISTRATOR'));
                    if ($base['status'] == 2) {
                        foreach ($admin_uids as $admin_uid) {
                            D('Common/Message')->sendMessage($admin_uid, $title = '应用商店模块提交提醒', "{$user['nickname']}提交了新的主题《{$base['title']}》，请到后台审核。", 'admin/appstore/verify', array(), is_login(), 2);
                        }
                        $this->success('商品创建成功。请耐心等待审核，在此期间，您可以上传一个版本，只有审核通过，且有新版本的商品才能够显示在前台。', U('appstore/index/themeDetail', array('id' => $goods_id)));
                    } else {
                        $this->success('商品创建成功。');
                    }


                }

            } else {
                $this->error('验证失败');
            }

        } else {
            $this->checkAuth(null, -1, '您不具备发布主题的权限，无法发布主题。');
            $id = intval($id);
            $data = array();
            if ($id != 0) {
                $data = D('AppstoreTheme')->getById($id);

            }
            $this->checkCreatePermission($data);
            $obj = $this->buildBaseForm($form, $data, 3);

            /*兼容版本 compat 字段*/
            $form->add('label', 'label_compatible', 'compatible', '兼容浏览器');
            if ($data) {

                $obj = $form->add('checkboxes', 'compatible[]', array('ie8' => 'IE8', 'ie9' => 'ie9', 'ie10' => 'ie10', 'ie11' => 'ie11', 'ff' => 'firefox', 'chrome' => 'chrome', 'safari' => 'safari', 'edge'), decode_compat_to_array_from_db($data['compat']));
            } else {
                $obj = $form->add('checkboxes', 'compatible[]', array('ie8' => 'IE8', 'ie9' => 'ie9', 'ie10' => 'ie10', 'ie11' => 'ie11', 'ff' => 'firefox', 'chrome' => 'chrome', 'safari' => 'safari', 'edge'));
            }

            $this->buildEditor($form, $data);


            /*渲染*/
            $form = $form->render('*horizontal', true, array('class' => 'form-horizontal'));

            $this->assign('form', $form);
            $this->assign('current', 'theme');
            $this->assign('data',$data);
            $this->display();
        }

    }

    public function  addmodule($id = 0)
    {
        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {
            // 验证表单
            if ($form->validate()) {
                $base = array(); //基本数据
                $resource = array(); //资源数据
                $module = array(); //插件数据
                $id = intval($id);
                if ($id != 0) {
                    $base = D('AppstoreGoods')->find($id);
                    $this->checkPermission($base); //检查权限，防止越权修改
                    $base = $this->getBaseData($base);
                    D('AppstoreGoods')->save($base);
                    $resource = $this->getResourceData($base['id'], $resource);
                    D('AppstoreResource')->save($resource);
                    $module = $this->getModuleData($base['id'], $module);
                    D('AppstoreModule')->save($module);
                    $this->success('商品数据修改成功。', U('index/goodsDetail', array('id' => $id)));
                } else {

                    $base = $this->getBaseData($base);
                    $base['entity'] = 2;
                    $base['uid'] = get_uid();
                    $base['create_time'] = time();
                    $base = $this->getGoodsStatus($base);
                    $goods_id = D('AppstoreGoods')->add($base);
                    if ($goods_id == 0) {
                        $this->error('创建失败。');
                    }
                    $resource = $this->getResourceData($goods_id, $resource);
                    D('AppstoreResource')->add($resource);
                    $module = $this->getModuleData($goods_id, $module);
                    $result = D('AppstoreModule')->add($module);

                    $this->iniDev();

                    $user = query_user(array('nickname'));
                    $admin_uids = explode(',', C('USER_ADMINISTRATOR'));
                    if ($base['status'] == 2) {
                        foreach ($admin_uids as $admin_uid) {
                            D('Common/Message')->sendMessage($admin_uid, $title = '应用商店模块提交提醒', "{$user['nickname']}提交了新的模块《{$base['title']}》，请到后台审核。", 'admin/appstore/verify', array(), is_login(), 2);
                            $this->success('商品创建成功。请耐心等待审核，在此期间，您可以上传一个版本，只有审核通过，且有新版本的商品才能够显示在前台。', U('index/moduleDetail', array('id' => $goods_id)));
                        }
                    } else {
                        $this->success('商品创建成功。');
                    }
                }
            } else {
                $this->error('验证失败');
            }
        } else {
            $this->checkAuth(null, -1, '您不具备发布模块的权限，无法发布模块。');
            $id = intval($id);
            $data = array();
            if ($id != 0) {
                $data = D('AppstoreModule')->getById($id);

            }
            $this->checkCreatePermission($data);
            $obj = $this->buildBaseForm($form, $data);


            /*插件扩展字段*/
            /*名称 title 字段*/
            $form->add('label', 'label_rely', 'rely', '依赖的模块');
            $obj = $form->add('text', 'rely', $data['rely'], array('autocomplete' => 'off', 'style' => 'width:350px'));
            $form->add('note', 'note_rely', 'rely', '必填，请填写您的模块所依赖的模块，如果您的模块完全独立则不需要填，逗号分隔<br/>例如：Weibo,Forum。', array('style' => 'width:500px'));
            $this->buildEditor($form, $data);

            /*渲染*/
            $form = $form->render('*horizontal', true, array('class' => 'form-horizontal'));

            $this->assign('form', $form);
            $this->assign('current', 'module');
            $this->assign('data',$data);
            $this->display();
        }


    }

    public function  addservice($id = 0)
    {

        $form = new \Vendor\zebra\Zebra_Form('form');
        if (IS_POST) {
            // 验证表单
            if ($form->validate()) {
                $base = array(); //基本数据
                $resource = array(); //资源数据
                $service = array(); //插件数据
                $id = intval($id);
                if ($id != 0) {
                    $base = D('AppstoreGoods')->find($id);
                    $this->checkPermission($base); //检查权限，防止越权修改
                    $base = $this->getBaseData($base);
                    D('AppstoreGoods')->save($base);
                    $resource = $this->getResourceData($base['id'], $resource);
                    D('AppstoreResource')->save($resource);
                    $service = $this->getServiceData($base['id'], $service);
                    D('AppstoreService')->save($service);
                    $this->success('服务修改成功。', U('index/goodsDetail', array('id' => $id)));
                } else {

                    $base = $this->getBaseData($base);
                    $base['uid'] = get_uid();
                    $base['entity'] = 4;
                    $base['create_time'] = time();
                    $base = $this->getGoodsStatus($base);

                    $goods_id = D('AppstoreGoods')->add($base);
                    if ($goods_id == 0) {
                        $this->error('创建失败。');
                    }
                    $resource = $this->getResourceData($goods_id, $resource);
                    D('AppstoreResource')->add($resource);
                    $service = $this->getServiceData($goods_id, $service);
                    $result = D('AppstoreService')->add($service);

                    $this->iniDev();

                    $user = query_user(array('nickname'));
                    $admin_uids = get_auth_user('Appstore/Admin/manage');
                    if ($base['status'] == 2) {
                        D('Common/Message')->sendMessage($admin_uids, $title = '应用商店服务提交提醒', "{$user['nickname']}提交了新的服务《{$base['title']}》，请到后台审核。", 'admin/appstore/verify', array(), is_login(), 2);

                        $this->success('服务创建成功。请耐心等待审核，在此期间，您可以创建价格方案，只有审核通过，服务才能够显示在前台。', U('index/pluginDetail', array('id' => $goods_id)));
                    } else {
                        $this->success('服务创建成功。', U('index/goodsDetail', array('id' => $goods_id)));
                    }


                }

            } else {
                $this->error('验证失败');
            }

        } else {


            $id = intval($id);
            $data = null;
            if ($id != 0) {
                $data = D('AppstorePlugin')->getById($id);

            }
            $this->checkCreatePermission($data);
            $obj = $this->buildBaseServiceForm($form, $data, 4);

            $this->buildServiceEditor($form, $data);

            $form->clientside_validation(
                array(
                    'close_tips' => false, //  don't show a "close" button on tips with error messages
                    'on_ready' => false, //  no function to be executed when the form is ready
                    'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                    'scroll_to_error' => true, //  don't scroll the browser window to the error message
                    'tips_position' => 'right', //  position tips with error messages to the right of the controls
                    'validate_on_the_fly' => true, //  don't validate controls on the fly
                    'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
                )
            );
            // 提交按钮
            $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));

            /*渲染*/
            $form = $form->render('*horizontal', true, array('class' => 'form-horizontal'));
            $this->assign('current', 'service');
            $this->assign('form', $form);
            $this->assign('data',$data);
            $this->display();
        }


    }


    private function getMoney($form, $version = '')
    {


        /*售价 need_buy 字段*/
        $form->add('label', 'label_need_buy', 'need_buy', '售价', null);
        $obj = $form->add('select', 'need_buy', $version ? $version['need_buy'] : 0);

        $obj->add_options(array(0 => '免费', 1 => '收费'));

        $obj->set_rule(array(
            'required' => array('error', '售价必须填写。'),
            'length' => array(1, 20, 'error', '长度必须在1-20个字之间。'),
            'regexp' => array('^(([1-9]\d{0,9})|0)(\.\d{1,2})?$', 'error', '必须输入一个有效的金额')
        ));
        // $form->add('note', 'note_need_buy', 'need_buy', '填0则为免费。单位人民币，最多两位小数。', array('style' => 'width:400px'));
        $form->add('note', 'note_need_buy2', 'need_buy', '如果收费，请务必完善开发者资料，让用户可以联系到您。', array('style' => 'width:400px'));

        $version && $this->assign('version', $version);

        $score = D('Ucenter/Score')->getTypeList(array('status' => 1));
        $roles = D('Admin/Role')->selectByMap(array('status' => 1));

        $this->assign('score', $score);
        $this->assign('roles', $roles);
        $html = $this->fetch('_versionmoney');
        $form->add('userDefined', $html);
        return $form;
    }


    public function my()
    {
        $verifing = D('AppstoreGoods')->getLimit(array('status' => 2, 'uid' => is_login()), 10);
        $this->assign('verifing', $verifing);

        $selling = D('AppstoreGoods')->getLimit(array('status' => 1, 'uid' => is_login()), 10);

        $this->assign('selling', $selling);
        $dev = $this->getPercent();

        $this->assign('dev', $dev);
        $this->display();
    }

    public function settip()
    {
        $aTip = I('post.tip', 0, 'intval');
        $developerModel = D('AppstoreDeveloper');
        $developer = $developerModel->find(is_login());
        if ($developer) {

            $developer['refuse_message'] = !$aTip;
            $rs = $developerModel->save($developer);
        } else {
            $developer['uid'] = is_login();
            $developer['refuse_message'] = !$aTip;
            $rs = $developerModel->add($developer);
        }

        if ($rs === false) {
            $this->error('数据库写入失败。');
        } else {
            $this->success('保存成功。');
        }

    }

    public function verify()
    {
        if (IS_POST) {
            $error = array();
            if (I('name') == '') {
                $error[] = $this->getError('请输入姓名');
            }
            if (I('qq') == '') {
                $error[] = $this->getError('请输入QQ号');
            }
            if (I('phone') == '') {
                $error[] = $this->getError('请输入电话号码');
            }
            if (I('goodat') == '') {
                $error[] = $this->getError('请输入擅长技能');
            }
            if (I('des') == '') {
                $error[] = $this->getError('请输入自我介绍');
            }
            if (count($error) > 0) {
                $this->error($error);
            }

            $dev['uid'] = is_login();
            $dev['name'] = I('name');
            $dev['qq'] = I('qq');
            $dev['kf_qq'] = I('kf_qq');
            $dev['phone'] = I('phone');
            $dev['goodat'] = I('goodat');
            $dev['des'] = I('des');
            D('AppstoreDeveloper')->add($dev, null, 1);
            $this->success(<<<string
    <div class="alert alert-success alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
   保存成功！
</div>
string
            );

        }
        $dev = D('AppstoreDeveloper')->find(is_login());
        $this->assign('dev', $dev);


        $this->display();
    }

    /**
     * 店铺提交审核
     */
    public function submitVerify()
    {
        $shopModel = D('Appstore/AppstoreShop');
        $shop = $shopModel->find(get_uid());
        if (!$shop) {
            $this->error($this->getError('请先保存后再提交审核。'));
        } else {
            $shop['status'] = 2;
            $result = $shopModel->save($shop);
            if ($result === false) {
                $this->error($this->getError('数据写入错误。'));
            } else {
                $user = query_user(array('nickname'));
                $uids = get_auth_user('Appstore/Admin/manage');
                D('Common/Message')->sendMessageWithoutCheckSelf($uids, '云市场开店申请', $user['nickname'] . '提交了店铺审核，店名' . $shop['title'], 'Admin/Appstore/shop', array('id' => $shop['uid']));
                $this->success($this->getSuccess('提交审核成功，请等待管理员审核。'));
            }

        }
    }

    public function shop()
    {
        $this->setTitle('我的店铺——云市场控制台');
        if (IS_POST) {
            $aTitle = I('post.title', '', 'text');
            $aAd = I('post.ad', '', '', 'text');
            $aLogo = I('post.logo', 0, 'intval');
            $aWebsite = I('post.website', 0, 'text');
            $error = array();
            if ($aTitle == '') {
                $error[] = $this->getError('请输入店名');
            }
            if ($aAd == '') {
                $error[] = $this->getError('请输入一句话广告词');
            }
            if ($aLogo == '') {
                $error[] = $this->getError('请上传店铺logo');
            }
            if (count($error) > 0) {
                $this->error($error);
            }
            $shop['uid'] = get_uid();
            $shop['title'] = $aTitle;
            $shop['ad'] = $aAd;
            $shop['logo'] = $aLogo;
            $shop['website'] = $aWebsite;
            $shop['goods_count'] = D('AppstoreGoods')->where(array('uid' => is_login(), 'status' => 1))->count();
            $shop['sales_count'] = D('AppstoreGoods')->where(array('uid' => is_login(), 'status' => 1))->sum('sales');
            $shop['sales_count'] = $shop['sales_count'] == null ? 0 : $shop['sales_count'];
            $shop['update_time'] = time();
            $shopModel = D('Appstore/AppstoreShop');
            if ($shopModel->find(get_uid())) {
                $result = $shopModel->save($shop);
            } else {
                $shop['create_time'] = time();
                $result = $shopModel->add($shop);
            }
            if ($result === false) {
                $this->error($this->getError('数据库写入失败。'));
            } else {
                $this->success($this->getSuccess());
            }


        }
        $shop = D('AppstoreShop')->find(is_login());
        $this->assign('shop', $shop);


        $this->display();
    }

    private function getSuccess($tip = '保存成功！')
    {
        return <<<string
    <div class="alert alert-success alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    {$tip}
</div>
string;
    }

    private function getError($tip)
    {
        return
            <<<string
    <div class="alert alert-warning alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
  <strong>错误！</strong> {$tip}
</div>
string;
    }

    public function myplugin()
    {
        $verifing = D('AppstorePlugin')->getLimit(array('status' => 2, 'uid' => is_login(), 'entity' => 1), 1000, 'update_time desc', 1);


        $this->assign('verifing', $verifing);

        $selling = D('AppstorePlugin')->getList(array('status' => 1, 'uid' => is_login(), 'entity' => 1), 10, 'update_time desc', 1);

        $this->assign('selling', $selling);

        $this->display();
    }

    public function mymodule()
    {
        $verifing = D('AppstoreModule')->getLimit(array('status' => 2, 'uid' => is_login(), 'entity' => 1), 1000, 'update_time desc', 1);


        $this->assign('verifing', $verifing);

        $selling = D('AppstoreModule')->getList(array('status' => 1, 'uid' => is_login(), 'entity' => 1), 10, 'update_time desc', 1);

        $this->assign('selling', $selling);

        $this->display();
    }

    /**
     * @param $base
     * @param $v
     * @return array
     * @auth 陈一枭
     */
    private function getBaseData($base)
    {
        $base['title'] = text(I('post.title'));
        $base['summary'] = html(I('post.summary', '', 'html'));
        $cover=I('post.cover','','text');
        $cover_array=explode(',',$cover);
        $cover_array=array_map('intval',$cover_array);
        if(count($cover_array)>1){
            $base['cover'] = implode(',',$cover_array);
        }else{
            $base['cover'] = $cover_array[0];
        }

        $base['author'] = op_t(I('post.author'));
        $base['ad'] = I('post.ad', '', 'text');
        $base['type_id'] = intval(I('post.type_id'));
        $base['update_time'] = time();
        return $base;
    }

    /**
     * @param $goods_id
     * @param $resource
     * @return mixed
     * @auth 陈一枭
     */
    private function getResourceData($goods_id, $resource)
    {
        $resource['id'] = $goods_id;
        $resource['etitle'] = op_t(I('post.etitle'));
        $resource['demo'] = text(I('post.demo', '', 'text'));
        return $resource;
    }

    /**
     * @param $goods_id
     * @param $plugin
     * @return mixed
     * @auth 陈一枭
     */
    private function getPluginData($goods_id, $plugin)
    {
        $plugin['id'] = $goods_id;
        $plugin['hook'] = op_t(I('post.hook'));
        return $plugin;
    }

    /**获取服务数据
     * @param $goods_id
     * @param $service
     * @return mixed
     */
    private function getServiceData($goods_id,$service){
        $service['id'] = $goods_id;
        return $service;
    }

    /**
     * @param $goods_id
     * @param $plugin
     * @return mixed
     * @auth 陈一枭
     */
    private function getModuleData($goods_id, $module)
    {
        $module['id'] = $goods_id;
        $module['hook'] = text(I('post.rely'));
        return $module;
    }

    private function getThemeData($goods_id, $theme)
    {
        $module['id'] = $goods_id;
        $module['theme'] = text(I('post.theme'));
        return $module;
    }


    /**
     * @param $base
     * @auth 陈一枭
     */
    private function checkPermission($base)
    {
        if ($base['uid'] != is_login() && !check_auth('Appstore/Admin/manage')) {
            $this->error('请不要操作他人的商品。');
        }
    }

    public function checkCreatePermission($data)
    {
        if ($data == null) {
            $this->checkAuth(null, -1, '您不具备发布插件的权限，无法发布插件。');
        } else {
            if ($data['uid'] != is_login() && !check_auth('Appstore/Admin/manage')) {
                $this->error('请不要越权操作。');
            }
        }

    }

    /**
     * @return mixed
     * @auth 陈一枭
     */
    private function getPercent()
    {
        $dev = D('AppstoreDeveloper')->find(is_login());
        $total = 0;
        $filled = 0;
        foreach ($dev as $key => $v) {
            if (!in_array($key, explode(',', 'uid,status,refuse_message'))) {
                $total++;
                if ($v != '') {
                    $filled++;
                }
            }
        }
        $percent = $filled / $total * 100;

        $this->assign('percent', $percent);
        return $dev;
    }

    /**
     * @param $form
     * @param $data
     * @return mixed
     */
    public function buildBaseForm($form, $data, $entity = 2)
    {
        /*日志 log 字段*/
        $form->add('hidden', 'goods_id', $data['id']);

        /*名称 title 字段*/
        $form->add('label', 'label_title', 'title', '名称', null);
        $obj = $form->add('text', 'title', op_t($data['title']));
        $obj->set_rule(array(
            'required' => array('error', '名称必须填写。'),
            'length' => array(2, 20, 'error', '长度必须在2-20个字之间。')
        ));

        $form->add('note', 'note_title', 'title', '必填，最短2个字，最长20个字。', array('style' => 'width:200px'));


        /*英文名称 etitle 字段*/
        $form->add('label', 'label_etitle', 'etitle', '英文名称', null);
        $obj = $form->add('text', 'etitle', $data['etitle']);
        $obj->set_rule(array(
            'required' => array('error', '名称必须填写。'),
            'length' => array(1, 20, 'error', '长度必须在1-20个字之间。')
        ));
        $form->add('note', 'note_etitle', 'etitle', '必填，最短1个字，最长20个字。尽量不要与其他模块重名。', array('style' => 'width:400px'));


        /*作者 author 字段*/
        $form->add('label', 'label_author', 'author', '作者', null);
        $obj = $form->add('text', 'author', $data['author']);
        $obj->set_rule(array(
            'length' => array(2, 20, 'error', '长度必须在2-20个字之间。')
        ));
        $form->add('note', 'note_author', 'author', '填写该插件的作者名称，如果不填则为当前登录ID。', array('style' => 'width:300px'));

        /*营销广告 ad 字段*/
        $form->add('label', 'label_ad', 'ad', '一句话广告词', null);
        $obj = $form->add('text', 'ad', $data['ad'], array('style' => 'width:350px'));
        $obj->set_rule(array(
            'length' => array(1, 50, 'error', '50个汉字之内。')
        ));
        $form->add('note', 'note_ad', 'ad', '展示在列表中，可以作为简介', array('style' => 'width:600px'));

        /*分类 type_id 字段*/
        $options = get_type_select($entity);
        $form->add('label', 'label_type', 'type_id', '分类');
        $obj = $form->add('select', 'type_id', $data['type_id']);
        $obj->add_options($options, true);
        $obj->set_rule(array(
            'required' => array('error', '请务必选择分类。')
        ));


        /*作者 author 字段*/
        $form->add('label', 'label_demo', 'demo', '在线演示', null);
        $obj = $form->add('text', 'demo', $data['demo'], array('style' => 'width:350px'));
        $obj->set_rule(array(
            'length' => array(2, 250, 'error', '以 http:// 开头，长度必须在250个字母之内。')
        ));
        $form->add('note', 'note_demo', 'demo', '以 http:// 开头，填写一个演示网站的地址，有演示可以大幅度提高销量', array('style' => 'width:600px'));

        return $obj;
    }

    /**
     * @param $form
     * @param $data
     * @return mixed
     */
    public function buildBaseServiceForm($form, $data, $entity = 2)
    {
        /*日志 log 字段*/
        $form->add('hidden', 'goods_id', $data['id']);

        /*名称 title 字段*/
        $form->add('label', 'label_title', 'title', '名称', null);
        $obj = $form->add('text', 'title', op_t($data['title']));
        $obj->set_rule(array(
            'required' => array('error', '名称必须填写。'),
            'length' => array(2, 20, 'error', '长度必须在2-20个字之间。')
        ));

        $form->add('note', 'note_title', 'title', '必填，最短2个字，最长20个字。', array('style' => 'width:200px'));


        /*营销广告 ad 字段*/
        $form->add('label', 'label_ad', 'ad', '一句话广告词', null);
        $obj = $form->add('text', 'ad', $data['ad'], array('style' => 'width:350px'));
        $obj->set_rule(array(
            'length' => array(1, 50, 'error', '50个汉字之内。')
        ));
        $form->add('note', 'note_ad', 'ad', '展示在列表中，可以作为简介', array('style' => 'width:600px'));

        /*分类 type_id 字段*/
        $options = get_type_select($entity);
        $form->add('label', 'label_type', 'type_id', '分类');
        $obj = $form->add('select', 'type_id', $data['type_id']);
        $obj->add_options($options, true);
        $obj->set_rule(array(
            'required' => array('error', '请务必选择分类。')
        ));


        return $obj;
    }

    /**
     * @param $form
     * @param $data
     */
    public function buildEditor($form, $data)
    {
        /*简介 summary 字段*/
        $form->add('label', 'label_summary', 'summary', '商品介绍');
        $obj = $form->add('ueditor', 'summary', html($data['summary']), array('style' => 'width:800px;height:600px'));
        $obj->set_rule(array(
            'length' => array(10, 5000000, 'error', '模块说明不得超过5000000字。')
        ));
        $form->add('note', 'note_summary', 'summary', '必填，请系统化地介绍一下您的模块，有助于销量。', array('style' => 'width:500px,height:500px '));



        $form->clientside_validation(
            array(
                'close_tips' => false, //  don't show a "close" button on tips with error messages
                'on_ready' => false, //  no function to be executed when the form is ready
                'disable_upload_validation' => true, //  using a custom plugin for managing file uploads
                'scroll_to_error' => true, //  don't scroll the browser window to the error message
                'tips_position' => 'right', //  position tips with error messages to the right of the controls
                'validate_on_the_fly' => true, //  don't validate controls on the fly
                'validate_all' => false, //  show error messages one by one upon trying to submit an invalid form
            )
        );
        // 提交按钮
        $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));
    }

    /**
     * @param $form
     * @param $data
     */
    public function buildServiceEditor($form, $data)
    {
        /*简介 summary 字段*/
        $form->add('label', 'label_summary', 'summary', '服务介绍');
        $obj = $form->add('ueditor', 'summary', html($data['summary']), array('style' => 'width:800px;height:600px'));
        $obj->set_rule(array(
            'length' => array(10, 5000000, 'error', '模块说明不得超过5000000字。')
        ));
        $form->add('note', 'note_summary', 'summary', '必填，请系统化地介绍一下您的模块，有助于销量。', array('style' => 'width:500px,height:500px '));

        // 提交按钮
        $form->add('submit', 'btnsubmit', '提交', array('class' => 'btn-primary'));
    }

    /**
     * @param $base
     * @return mixed
     */
    public function getGoodsStatus($base)
    {
        if (check_auth('Appstore/Admin/manage')) {
            $base['status'] = 1;
            return $base;
        } else {
            $base['status'] = C('INIT_STATUS');
            return $base;
        }
    }

    public function checkWebsite()
    {
        $aWebsite = I('post.website', '', 'text');
        $websiteModel = D('AppstoreWebsite');
        $check = $websiteModel->checkWebsiteIsExist($aWebsite);
        if ($check) {
            $this->error('验证失败,该域名已经被绑定');
        }
        $return = $this->visitUrl($aWebsite);
        if ($return[0] == 200) {
            $this->success('验证成功');
        } else {
            $this->error('验证失败，无法找到appstore.txt');
        }
    }


    private function visitUrl($url)
    {

        if (!is_bool(strpos($url, 'https://'))) {
            $url = $url . '/appstore.txt';
        } else {
            $url = 'http://' . $url . '/appstore.txt';
        }

        $requester = new requester($url);
        $requester->charset = "utf-8";
        $requester->content_type = 'application/x-www-form-urlencoded';
        $requester->data = '';
        $requester->enableCookie = true;
        $requester->enableHeaderOutput = false;
        $requester->method = "get";
        $arr = $requester->request();
        return $arr;
    }


}